package cn.zwk.service.impl;

import cn.zwk.common.to.es.SkuEsModel;
import cn.zwk.mapping.ProductMapping;
import cn.zwk.service.SaveService;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class SaveServiceImpl implements SaveService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public void saveProduct(List<SkuEsModel> skuEsModels) {
        BulkRequest request = new BulkRequest();
        skuEsModels.forEach(sku -> {
            new IndexRequest(ProductMapping.INDEX_NAME).id(sku.getSkuId().toString()).source(JSON.toJSONString(sku), XContentType.JSON);
            request.add(
                    new IndexRequest(ProductMapping.INDEX_NAME)
                            .id(sku.getSkuId().toString())
                            .source(JSON.toJSONString(sku), XContentType.JSON)
            );
        });
        log.info("商品上架请求：{}", JSON.toJSONString(skuEsModels));
        try {
            BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
            boolean hasFailures = bulk.hasFailures();
            if (hasFailures) {
                log.error("商品上架错误：{}", bulk.buildFailureMessage());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
